package LandR.personal.personalHelp.function_mysql;

import java.sql.*;

/**
 * 这个类包含一些有关数据库接口的方法
 * 1）static Connection getConnection() 连接数据库返回Connection对象
 * 2）static PreparedStatement getPrepareStatement(String sql) 获取prepareStatement接口
 * 3）static void close（Connection conn） 关闭connection接口
 * 4）static void close(PreparedStatement pstmt) 关闭prepareStatement接口
 * 5）static void close(ResultSet rs)  关闭resultset接口
 */

public class ConnectionMethod {
    //1.getConnection 获取数据库连接的方法，返回一个Connection对象
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
        final String URL = "jdbc:mysql://123.57.3.195:3306/YDYP?characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
        final String username = "root";
        final String password = "ZAMTYR1314";
        Connection conn = DriverManager.getConnection(URL, "root", "ZAMTYR1314");
        if (conn == null) {
            System.out.println("创建连接失败");
            close(conn);
            return null;
        } else {
            System.out.println("创建连接成功");
            return conn;
        }
    }

    //2.getPrepareStatement  获取statement接口方法
    public static PreparedStatement getPrepareStatement(String sql) throws SQLException, ClassNotFoundException {
        Connection conn = getConnection();
        PreparedStatement ppsm = (PreparedStatement) conn.prepareStatement(sql);
        return ppsm;
    }

    public static void close(PreparedStatement pstmt) {
        if (pstmt != null) {                        //避免出现空指针异常
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

}
